use super::Task;
use crate::config::AccountConfig;
use crate::http_client::HttpClientBuilder;
use log::info;
use reqwest;
use unescape::unescape;

pub struct FeituTask;

impl FeituTask {
    async fn call_feitu_api_sign(
        &self,
        account: &AccountConfig,
        task_proxy: Option<&String>,
    ) -> Result<(), String> {
        info!("调用飞兔API：账号 {} 开始签到", account.nickname);

        let client = HttpClientBuilder::build_with_proxy(
            task_proxy,
            account.proxy.as_ref(),
        )?;

        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(
            "accept",
            "*/*"
                .parse()
                .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?,
        );
        headers.insert(
            "accept-language",
            "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"
                .parse()
                .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?,
        );
        headers.insert("authorization", account.authorization.parse()
            .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?);
        headers.insert(
            "cache-control",
            "no-cache"
                .parse()
                .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?,
        );
        headers.insert(
            "origin",
            "https://feitu.im"
                .parse()
                .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?,
        );
        headers.insert(
            "pragma",
            "no-cache"
                .parse()
                .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?,
        );
        headers.insert(
            "priority",
            "u=1, i"
                .parse()
                .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?,
        );
        headers.insert(
            "referer",
            "https://feitu.im/"
                .parse()
                .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?,
        );
        headers.insert(
            "sec-ch-ua",
            "\"Chromium\";v=\"140\", \"Not=A?Brand\";v=\"24\", \"Microsoft Edge\";v=\"140\""
                .parse()
                .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?,
        );
        headers.insert(
            "sec-ch-ua-mobile",
            "?0".parse()
                .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?,
        );
        headers.insert(
            "sec-ch-ua-platform",
            "\"Windows\""
                .parse()
                .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?,
        );
        headers.insert(
            "sec-fetch-dest",
            "empty"
                .parse()
                .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?,
        );
        headers.insert(
            "sec-fetch-mode",
            "cors"
                .parse()
                .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?,
        );
        headers.insert(
            "sec-fetch-site",
            "same-site"
                .parse()
                .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?,
        );
        headers.insert("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0".parse()
            .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?);

        let response = client
            .request(
                reqwest::Method::GET,
                "https://api-cdn.feitu.im/ft/gateway/cn/user/sign",
            )
            .headers(headers)
            .send()
            .await
            .map_err(|e: reqwest::Error| e.to_string())?;

        let body = response
            .text()
            .await
            .map_err(|e: reqwest::Error| e.to_string())?;
        let decoded = unescape(&body).ok_or_else(|| "解码失败".to_string())?;
        info!("账号 {} 签到成功: {}", account.nickname, decoded);

        Ok(())
    }
    async fn call_feitu_api_get_list(
        &self,
        account: &AccountConfig,
        task_proxy: Option<&String>,
    ) -> Result<(), String> {
        info!("调用飞兔API：账号 {} 获取流量详情", account.nickname);

        let client = HttpClientBuilder::build_with_proxy(
            task_proxy,
            account.proxy.as_ref(),
        )?;

        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(
            "accept",
            "*/*"
                .parse()
                .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?,
        );
        headers.insert(
            "accept-language",
            "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"
                .parse()
                .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?,
        );
        headers.insert("authorization", account.authorization.parse()
            .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?);
        headers.insert(
            "cache-control",
            "no-cache"
                .parse()
                .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?,
        );
        headers.insert(
            "origin",
            "https://feitu.im"
                .parse()
                .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?,
        );
        headers.insert(
            "pragma",
            "no-cache"
                .parse()
                .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?,
        );
        headers.insert(
            "priority",
            "u=1, i"
                .parse()
                .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?,
        );
        headers.insert(
            "referer",
            "https://feitu.im/"
                .parse()
                .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?,
        );
        headers.insert(
            "sec-ch-ua",
            "\"Chromium\";v=\"140\", \"Not=A?Brand\";v=\"24\", \"Microsoft Edge\";v=\"140\""
                .parse()
                .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?,
        );
        headers.insert(
            "sec-ch-ua-mobile",
            "?0".parse()
                .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?,
        );
        headers.insert(
            "sec-ch-ua-platform",
            "\"Windows\""
                .parse()
                .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?,
        );
        headers.insert(
            "sec-fetch-dest",
            "empty"
                .parse()
                .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?,
        );
        headers.insert(
            "sec-fetch-mode",
            "cors"
                .parse()
                .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?,
        );
        headers.insert(
            "sec-fetch-site",
            "same-site"
                .parse()
                .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?,
        );
        headers.insert("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0".parse()
            .map_err(|e: reqwest::header::InvalidHeaderValue| e.to_string())?);

        let response = client
            .request(
                reqwest::Method::GET,
                "https://api-cdn.feitu.im/ft/gateway/cn/user/getSignList",
            )
            .headers(headers)
            .send()
            .await
            .map_err(|e: reqwest::Error| e.to_string())?;

        let body = response
            .text()
            .await
            .map_err(|e: reqwest::Error| e.to_string())?;
        let decoded = unescape(&body).ok_or_else(|| "解码失败".to_string())?;
        info!("账号 {} 获取流量详情成功: {}", account.nickname, decoded);

        Ok(())
    }
}

#[async_trait::async_trait]
impl Task for FeituTask {
    fn get_name(&self) -> String {
        "feitu".to_string()
    }

    async fn execute(&self, account: &AccountConfig, task_proxy: Option<&String>) -> Result<(), String> {
        self.call_feitu_api_sign(account, task_proxy)
            .await
            .map_err(|e| format!("账号 {} 签到失败: {}", account.nickname, e))?;
        self.call_feitu_api_get_list(account, task_proxy)
            .await
            .map_err(|e| format!("账号 {} 获取流量列表失败: {}", account.nickname, e))
    }
}
